//The following example duplicates an open descriptor:
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <errno.h>

void print_file_id(int file_descriptor) {
  struct stat info;
  if (fstat(file_descriptor, &info) != 0)
    fprintf(stderr, "stat() error for file_descriptor %d: %s\n",
            strerror(errno));
  else
    printf("The file id of file_descriptor %d is %d\n",
           file_descriptor,(int) info.st_ino);
}

main() {
  int file_descriptor, file_descriptor2;
  char fn[]="original.file";

  /* create original file */
  if((file_descriptor = creat(fn,S_IRUSR | S_IWUSR)) < 0)
    perror("creat() error");
  /* generate a duplicate file descriptor of file_descriptor */
  else {
    if ((file_descriptor2 = dup(file_descriptor)) < 0)
      perror("dup() error");
    /* print resulting information */
    else {
      print_file_id(file_descriptor);
      print_file_id(file_descriptor2);
      puts("The file descriptors are different but");
      puts("they point to the same file.");
      close(file_descriptor);
      close(file_descriptor2);
    }
    unlink(fn);
  }
}
